<?php

declare(strict_types=1);

namespace app\admin\controller;
use app\service\RedisSet;
use app\common\AdminController;
use app\admin\model\Role as RoleDB;
use think\Request;

class Role extends AdminController
{
  protected $redisInit;
  protected $field = ['id', 'role_name', 'role_key', 'role_sort', 'status', 'create_time', 'update_time'];
  protected $allowField = ['role_name', 'role_key', 'role_sort', 'status'];
  protected function initialize()
  {
    $this->model = new RoleDB();
  }

  public function list(array $rule = [], array $field = [], array $association = [], array $hidden = [])
  {
    $rule = [
      "roleName" => [
        "mode" => "like",
        "field" => "role_name",
      ],
      "roleKey" => [
        "mode" => "like",
        "field" => "role_key",
      ],
      "status" => [
        "mode" => "="
      ],
      "createTime" => [
        "mode" => "between",
        "field" => "create_time",
      ],
    ];
    return parent::list($rule, $this->field);
  }

  public function add(array $allowField = [], array $association = [], $data = [], $returnId = true)
  {
    $datas = input('post.');
    $allowField = $this->allowField;
    $allowField[] = 'create_time';
    $allowField[] = 'create_by';
    $association = [
      'menu' => [
        'save' => $datas['menu']
      ]
    ];
    $res = parent::add($allowField, $association, $data, $returnId);
    $dataRes = $res instanceof \think\response\Json ? $res->getData() : [];
    if ($dataRes['code'] == 200) {
      RedisSet::initPermsById($this->model, $dataRes['data']['id']);
    }
    return $res;
  }

  public function update(array $allowField = [], array $where = [], array $association = [], $data = [])
  {
    $datas = input('post.');
    if ($datas['id'] == $this->adminRoleId) {
      return error('管理员角色不能修改');
    }
    try {
      Validate([
        'roleKey' => 'require|max:20|unique:role,role_key,' . $datas['id'] . ',id',
      ])->message([
            'roleKey.require' => '权限字符不能为空',
            'roleKey.max' => '权限字符最大长度20',
            'roleKey.unique' => '权限字符已存在',
          ])->check($datas);
    } catch (\Throwable $th) {
      // throw $th;
      return error($th->getMessage());
    }
    $allowField = $this->allowField;
    $allowField[] = 'update_time';
    $allowField[] = 'update_by';
    $newMenu = $datas['menu'];
    $currentMenu = \app\admin\model\RoleMenu::where('role_id', $datas['id'])->column('menu_id');
    $menuToAdd = array_diff($newMenu, $currentMenu);
    $menuToRemove = array_diff($currentMenu, $newMenu);
    $association = [
      'menu' => [
        'save' => $menuToAdd,
        'remove' => $menuToRemove
      ]
    ];
    $res = parent::update($allowField, [], $association);
    $dataRes = $res instanceof \think\response\Json ? $res->getData() : [];
    if ($dataRes['code'] == 200) {
      RedisSet::initPermsById($this->model, $datas['id']);
    }
    return $res;
  }

  public function del($ids, $type = false, $where = [])
  {
    $isId = explode(',', $ids);
    if (in_array($this->adminRoleId, $isId)) {
      return error('删除失败,此角色不能删除');
    }
    $res = parent::del($ids);
    $dataRes = $res instanceof \think\response\Json ? $res->getData() : [];
    if ($dataRes['code'] == 200) {
      RedisSet::delPermsById($isId);
    }
    return $res;
  }

  public function get($id, array $field = [], array $where = [], array $association = [], array $hidden = [])
  {
    if ($id == $this->adminRoleId) {
      return error('管理员角色不能修改');
    }
    return parent::get($id, $this->field);
  }
}
